package com.muhuahealth.controller;

import com.muhuahealth.entity.AdminEntity;
import com.muhuahealth.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author GSK
 * @version 1.0
 * @date 2020/12/30 21:08
 */
@Slf4j
@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    AdminService adminService;

    //输入网址显示登录页面，若只有下边的login方法，由于传递了两个参数前端未收到会报错无法正确显示页面
    @GetMapping({"/login"})
    public String login(){
        return "login";
    }

    @GetMapping({"", "/", "/index", "/index.html"})
    public String index(HttpServletRequest request){
        request.setAttribute("path","index");
        log.info("跳转到主页面");
        return "index";
    }

    @PostMapping(value = "/login")
    public String login( @RequestParam("userName") String userName,
                         @RequestParam("password") String password,
                        @RequestParam("verifyCode") String verifyCode,
                        HttpSession httpSession){
//        Map<String,Object> map = new HashMap<>();
        if(StringUtils.isEmpty(verifyCode)){
            httpSession.setAttribute("errMsg","验证码不能为空！");
            return "login";
        }

        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)){
            httpSession.setAttribute("errMsg","用户名或密码不能为空！");
            return "login";
        }
        String captchaCode = httpSession.getAttribute("verifyCode") + "";
        if(StringUtils.isEmpty(captchaCode) || !verifyCode.equals(captchaCode)){
            httpSession.setAttribute("errMsg","验证码不正确！");
            return "login";
        }
        AdminEntity adminEntity = adminService.login(userName,password);
        if(adminEntity != null){
            httpSession.setAttribute("loginUser",adminEntity.getNickName());
            httpSession.setAttribute("userId",adminEntity.getId());
            return "redirect:/admin/index";

        }else {
            httpSession.setAttribute("errMsg","用户名或密码错误！登录失败");
            return "login";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute("loginUser");
        request.getSession().removeAttribute("userId");
        request.getSession().removeAttribute("errMsg");
        return "login";
    }
}
